package com.platform.modules.wallet.take;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.platform.common.config.PlatformConfig;
import com.platform.common.constant.AppConstants;
import com.platform.common.enums.YesOrNoEnum;
import com.platform.common.utils.redis.RedisUtils;
import com.platform.modules.sms.enums.SmsTemplateEnum;
import com.platform.modules.sms.service.SmsService;
import com.platform.modules.wallet.domain.WalletConfig;
import com.platform.modules.wallet.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class TotalSumTask {

    @Autowired
    private RedisUtils redisUtils;
    @Resource
    private WalletRechargeCashService rechargeCashService;
    @Resource
    private WalletTransferService transferService;
    @Resource
    private WalletRedPacketSubService redPacketSubService;
    @Resource
    private WalletDailyBillhService dailyBillhService;
    @Resource
    private WalletAccountService accountService;
    @Resource
    private SmsService smsService;
    @Resource
    private WalletConfigService configService;

    private String key = AppConstants.WALLET_TOTAL;

    @Scheduled(cron = "0 */5 * * * ?")//"0 5/10 9-23 * * ?"
    public void runClearRecord() {
        if (PlatformConfig.MASTER.equals(YesOrNoEnum.NO)) return;
        Integer rc = rechargeCashService.querySumAll();
        Integer bill = dailyBillhService.querySumAll();
        Integer account = accountService.querySumAll();
        Integer transfer = transferService.querySumAll();
        Integer redpacketSub = redPacketSubService.querySumAll();

        int difference = rc - bill - account - transfer - redpacketSub + 89522;
        String diff = String.valueOf(difference);
        String value = redisUtils.get(key);

        Dict dict = Dict.create()
                .set("code", diff);
        dict.set("corpId", "JX008281");
        dict.set("pwd", "123456");

        if (StrUtil.isBlank(value) || !value.equals(diff)) {
            redisUtils.set(key, diff, 60, TimeUnit.MINUTES);
            WalletConfig config = configService.getByKey("alarmPhone");
            try {
                smsService.doSendSms(config.getValue(), SmsTemplateEnum.VERIFY_CODE, dict);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
